package com.tgu.home_action.service.impl.admin;

import com.alibaba.excel.EasyExcel;
import com.tgu.home_action.dao.*;
import com.tgu.home_action.dao.admin.AdminVolunteerMapper;
import com.tgu.home_action.pojo.*;
import com.tgu.home_action.pojo.state.ResponseState;
import com.tgu.home_action.service.admin.AdminVolunteerService;
import com.tgu.home_action.service.listener.excel.VolunteerInformationListener;
import com.tgu.home_action.service.utils.FileService;
import com.tgu.home_action.service.utils.StringService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

@Validated
@Service
public class AdminVolunteerServiceImpl implements AdminVolunteerService {
    @Autowired
    private AdminVolunteerMapper adminVolunteerMapper;
    @Autowired
    private VolunteerInformationMapper volunteerInformationMapper;
    @Autowired
    private LiveNessMapper liveNessMapper;
    @Autowired
    private CaseMapper caseMapper;
    @Autowired
    private VolunteerMapper volunteerMapper;
    @Autowired
    private VolunteerCaseMapper volunteerCaseMapper;

    /**
     * 查询志愿者
     */
    @Override
    public ResponseData<Page<VolunteerInformation>> getVolunteer(VolunteerInformation volunteerInformation) {
        int sum = volunteerInformationMapper.getAccordVolunteerNum(volunteerInformation);
        if (volunteerInformation.getPageNo() == null || volunteerInformation.getPageSize() == null) {
            volunteerInformation.setPageNo(1);
            volunteerInformation.setPageSize(sum);
        }
        volunteerInformation.setStartSize((volunteerInformation.getPageNo() - 1) * volunteerInformation.getPageSize());
        List<VolunteerInformation> volunteerInformationList = volunteerInformationMapper.adminGetVolunteer(volunteerInformation);
        int pageNum;
        if (volunteerInformation.getPageSize() == 0) {
            pageNum = 0;
        } else {
            pageNum = sum / volunteerInformation.getPageSize();
            if (sum % volunteerInformation.getPageSize() > 0) {
                pageNum++;
            }
        }
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), new Page<>(volunteerInformation.getPageNo(), volunteerInformation.getPageSize(), pageNum, sum, volunteerInformationList));
    }

    /**
     * 通过id查询志愿者
     */
    @Override
    public ResponseData<VolunteerInformation> getVolunteerById(Integer id) {
        VolunteerInformation volunteerInformation = volunteerInformationMapper.adminGetVolunteerById(id);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), volunteerInformation);
    }

    /**
     * 插入单个志愿者
     */
    @Override
    public ResponseData<Object> insertVolunteer(VolunteerInformation volunteerInformation) {
        volunteerInformationMapper.insertVolunteer(volunteerInformation);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue());
    }

    /**
     * 通过excel插入志愿者
     */
    @Override
    public ResponseData<List<VolunteerInformation>> insertVolunteerByExcel(MultipartFile file) throws IOException {
        if (!FileService.isExcel(file.getOriginalFilename())) {
            return new ResponseData<>(ResponseState.FILE_FORMAT_ERROR.getMessage(), ResponseState.FILE_FORMAT_ERROR.getValue());
        }
        VolunteerInformationListener volunteerInformationListener = new VolunteerInformationListener(volunteerInformationMapper);
        EasyExcel.read(file.getInputStream(), VolunteerInformation.class, volunteerInformationListener).sheet().doRead();
        if (volunteerInformationListener.getFailList().size() != 0) {
            return new ResponseData<List<VolunteerInformation>>(ResponseState.SOME_INFORMATION_INSERT_ERROR.getMessage(), ResponseState.SOME_INFORMATION_INSERT_ERROR.getValue(), volunteerInformationListener.getFailList());
        }
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue());
    }

    /**
     * 查询志愿者活跃天数
     */
    @Override
    public ResponseData<Integer> getVolunteerLiveNessDay(Integer volunteerId) throws ParseException {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DAY_OF_MONTH, -30);
        String dayBefore30String = new SimpleDateFormat("yyyy-MM-dd").format(now.getTime());
        Timestamp dayBefore30 = new Timestamp(StringService.stingToDate(dayBefore30String, "yyyy-MM-dd").getTime());
        Integer day = liveNessMapper.getVolunteerLiveNessDay(volunteerId, dayBefore30);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), day);
    }

    /**
     * 查询志愿者参与的案件数
     */
    @Override
    public ResponseData<Integer> getVolunteerTotalCaseNum(Integer volunteerId) {
        Integer num = caseMapper.getVolunteerTotalCaseNum(volunteerId);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), num);
    }

    /**
     * 查询志愿者参与的已完成的案件数
     */
    @Override
    public ResponseData<Integer> getVolunteerFinishCaseNum(Integer volunteerId) {
        Integer num = caseMapper.getVolunteerFinishCaseNum(volunteerId);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), num);
    }

    /**
     * 修改志愿者信息
     */
    @Transactional
    @Override
    public ResponseData<Object> updateVolunteerInfo(VolunteerInformation volunteerInformation) {
        if (volunteerInformation.getVolunteer() != null) {
            if (volunteerInformation.getVolunteer().getState() != null && volunteerInformation.getVolunteer().getState() != 0 && volunteerInformation.getVolunteer().getState() != 1 && volunteerInformation.getVolunteer().getState() != 2) {
                return new ResponseData<>("state只能是1或2", ResponseState.PARAM_IS_ERROR.getValue());
            }
        }
        volunteerInformationMapper.adminUpdateInformation(volunteerInformation);
        if (volunteerInformation.getVolunteer() != null) {
            if (volunteerInformation.getVolunteer().getState() != null || volunteerInformation.getVolunteer().getPhone() != null) {
                Volunteer volunteer = volunteerMapper.getByInformationId(volunteerInformation.getId());
                if (volunteer == null) {
                    return new ResponseData<>(ResponseState.VOLUNTEER_NOT_REGISTER.getMessage(), ResponseState.VOLUNTEER_NOT_REGISTER.getValue());
                }
                volunteerInformation.getVolunteer().setId(volunteer.getId());
                volunteerMapper.updatePhoneAndState(volunteerInformation.getVolunteer());
            }
        }
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue());
    }

    /**
     * 更改头像
     */
    @Override
    public ResponseData<Object> updateAvatar(@NotNull(message = "id不能为空") Integer id, @NotNull(message = "avatarUrl不能为空") String avatarUrl) {
        Volunteer volunteer = volunteerMapper.getByInformationId(id);
        if (volunteer == null) {
            return new ResponseData<>(ResponseState.VOLUNTEER_NOT_REGISTER.getMessage(), ResponseState.VOLUNTEER_NOT_REGISTER.getValue());
        }
        volunteer.setAvatarUrl(avatarUrl);
        volunteerMapper.updateUserinfo(volunteer);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue());
    }

    @Override
    public ResponseData<Page<Case>> getVolunteerCases(Case nowCase) {
        int sum = caseMapper.getVolunteerAccordNumber(nowCase);
        if (nowCase.getPageNo() == null || nowCase.getPageSize() == null) {
            nowCase.setPageNo(1);
            nowCase.setPageSize(sum);
        }
        nowCase.setStartSize((nowCase.getPageNo() - 1) * nowCase.getPageSize());
        List<Case> cases = caseMapper.getVolunteerAccordCase(nowCase);
        int pageNum;
        if (nowCase.getPageSize() == 0) {
            pageNum = 0;
        } else {
            pageNum = sum / nowCase.getPageSize();
            if (sum % nowCase.getPageSize() > 0) {
                pageNum++;
            }
        }
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), new Page<>(nowCase.getPageNo(), nowCase.getPageSize(), pageNum, sum, cases));

    }

    /**
     * 删除志愿者用户
     */
    @Transactional
    @Override
    public ResponseData<Object> delVolunteer(Integer id) {
        VolunteerInformation information = volunteerInformationMapper.getById(id);
        if (information == null) {
            return new ResponseData<>(ResponseState.VOLUNTEER_NOT_EXIST.getMessage(), ResponseState.VOLUNTEER_NOT_EXIST.getValue());
        }
        volunteerInformationMapper.delVolunteer(information.getId());
        if (information.getVolunteerId() != null) {
            volunteerCaseMapper.deleteByVolunteerId(information.getVolunteerId());
            volunteerMapper.delVolunteer(information.getVolunteerId());
        }

        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue());
    }

    /**
     * 查询当日活跃的志愿者
     */
    @Override
    public ResponseData<List<Volunteer>> getLiveNessVolunteer() throws ParseException {
        Calendar now = Calendar.getInstance();
//        now.add(Calendar.DAY_OF_MONTH,-1);
        String todayString = new SimpleDateFormat("yyyy-MM-dd").format(now.getTime());
        Timestamp today = new Timestamp(StringService.stingToDate(todayString, "yyyy-MM-dd").getTime());
        List<Volunteer> volunteers = liveNessMapper.getLiveNessVolunteer(today);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), volunteers);
    }


}
